﻿using System;
using System.ServiceModel;
using System.Web.Compilation;
using System.Web.UI.WebControls;

namespace TeamFranceTriple
{
    public class WebServiceObjectDataSource : ObjectDataSource
    {
        public String EndpointConfigurationName { get; set; }
        public String EndpointContractTypeName { get; set; }

        public WebServiceObjectDataSource(): base()
        {
            ObjectCreating += new ObjectDataSourceObjectEventHandler(WebServiceObjectDataSource_ObjectCreating);
        }
        protected virtual void WebServiceObjectDataSource_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
        {
            String contractTypeName = String.IsNullOrEmpty(EndpointContractTypeName) ? TypeName : EndpointContractTypeName;
            
            Type serviceContractType = BuildManager.GetType(contractTypeName, true);
            
            Type channelFactoryType = typeof(ChannelFactory<>).MakeGenericType(new[] { serviceContractType });
            
            var factory = Activator.CreateInstance(channelFactoryType, new[] { EndpointConfigurationName });
            
            e.ObjectInstance = factory.GetType().GetMethod("CreateChannel", Type.EmptyTypes).Invoke(factory, null);
        }
    }
}